const server = require('../../../utils/server');
const App = getApp();

Page({
  data: {
    imgType: ['拍照', '相册', '拍照或相册'],
    sortName: '',
    sortDesc: '',
    sortsVal: 0,
    isEdit: false,
    sorts: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getSorts();
  },
  getSorts: function () {  //获取菜系分类
    let that = this;
    server.postJSON('getSorts', function (res) {
      if (res.data.status === 200) {
        that.setData({
          sorts: res.data.data
        })
      }
    });
  },
  witchs: function(e){
    this.setData({
      iswitch: e.detail.value
    })
  },
  bindPickerSorts: function (e) {
    console.log(e)
    this.setData({
      sortsVal: e.detail.value,
      sortName: '',
      sortDesc: '',
      isEdit: false
    })
  },
  editSorts: function(e){
    let data = e.currentTarget.dataset;
    let sorts = this.data.sorts;
    console.log(e)
    this.setData({
      sortName: sorts[data.idx].sortName,
      sortDesc: sorts[data.idx].sortDesc,
      isEdit: true
    })
  },
  delSorts: function(e){
    let that = this;
    let data = e.currentTarget.dataset;
    server.postJSON('delSorts', { _id: data.id }, function (res) {
      if (res.data.status === 200) {
        wx.showToast({
          icon: 'none',
          title: res.data.msg
        })
        that.setData({
          sorts: that.data.sorts.splice(data.idx, 1),
          sortsVal: 0
        })
        that.getSorts();
      }
    });
  },
  saveSorts: function (e) {
    let that = this;
    if (!e.detail.value.sortName) {
      return wx.showToast({
        icon: 'none',
        title: '菜谱名称不能为空',
      })
    }
    server.postJSON('saveSorts', e.detail.value, function (res) {
      if (res.data.status === 200) {
        that.getSorts();
        wx.showModal({
          title: '温馨提示',
          content: res.data.msg + ' 是否继续添加？',
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定')
              that.setData({
                sortName: '',
                sortDesc: '',
                sortsVal: 0
              })
            } else if (res.cancel) {
              console.log('用户点击取消')
              setTimeout(() => {
                wx.navigateBack()
              }, 200)
            }
          }
        })
      } else if (res.data.status === 201){
        return wx.showToast({
          icon: 'none',
          title: res.data.msg,
        })
      }
    });
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})